<template>

  <ContentWrap>
    批注Key：<input type="text" v-model="bookmarksign"/>
    单元格内容<input type="text" v-model="bookmarkname"/>
    替换内容：<input type="text" v-model="bookmarkValue"/>
    <el-button type="primary" plain @click="insertAnnotation()">
      <Icon icon="ep:plus" class="mr-5px" /> 插入批注
    </el-button>
    <el-button type="primary" plain @click="replaceAnnotation()">
      <Icon icon="ep:plus" class="mr-5px" /> 替换批注
    </el-button>
    <el-button type="primary" plain @click="changeAllAnnotationVisible(true)">
      <Icon icon="ep:plus" class="mr-5px" /> 显示批注
    </el-button>
    <el-button type="primary" plain @click="changeAllAnnotationVisible(false)">
      <Icon icon="ep:plus" class="mr-5px" /> 隐藏批注
    </el-button>
  </ContentWrap>

</template>

<script lang="ts" setup>

defineOptions({name: 'InsertAnnotation'})

const bookmarksign = ref('bookmark1');
const bookmarkname = ref("我是测试批注1");
const bookmarkValue = ref("书签替换内容");

const OnSheetSelectionChange = ()=>{
    let etApp = wps.EtApplication();
    let selection = etApp.ActiveWindow.Selection;
    bookmarksign.value = selection.Comment?.Text();
    bookmarkname.value = selection.Formula;
}


const insertAnnotation = async function () {
    // 插入文字型窗体域
    let etApp = wps.EtApplication();
    let selection = etApp.ActiveWindow.Selection;

    if(selection.Rows.Count > 1 || selection.Columns.Count > 1){
      alert("请选择一个单元格！")
      return
    }
    if(null == bookmarksign.value || "" == bookmarksign.value){
      alert("请输入 批注Key！")
      return
    }
    if(selection.Comment){
      let selection = etApp.ActiveWindow.Selection;
      selection.Comment?.Text(bookmarksign.value);
    }else {
      let myComment = selection.AddComment()
      myComment.Text(bookmarksign.value)
    }

    selection.Formula = bookmarkname.value ;

    // 添加成功给予提示
    alert("批注【" + bookmarkname.value + "】添加成功！");

}

const replaceAnnotation = async function () {
    // 插入文字型窗体域
    let etApp = wps.EtApplication();
    let selection = etApp.ActiveWindow.Selection;
    if (selection.Comment?.Text()) {
      selection.Formula = bookmarkValue.value ;
    }
}
const changeAllAnnotationVisible = async function (visibleFlag) {
    // 插入文字型窗体域
    let etApp = wps.EtApplication();
    let cmt = etApp.ActiveSheet.Comments
    for (let c = 1; c <= cmt.Count; c++) {
      cmt.Item(c).Visible = visibleFlag
    }
}

onBeforeUnmount(() => {
   wps.ApiEvent.RemoveApiEventListener("SheetSelectionChange");
})

wps.ApiEvent.AddApiEventListener("SheetSelectionChange", OnSheetSelectionChange);


</script>
